﻿Imports System.Data.SqlClient
Imports System.Web.Security
Imports System.Configuration
Imports System.Data.Sql
Imports System.Security.Cryptography
Imports System.Security.Principal


Partial Class admin_login
    Inherits System.Web.UI.Page

    Private _userid As Integer
    Public Property UserID() As Integer
        Get
            Return _userid
        End Get
        Set(ByVal value As Integer)
            _userid = value
        End Set
    End Property


    Dim connectionString As String = ConfigurationManager.ConnectionStrings("Henson Family").ConnectionString
    Dim objConn As New SqlConnection(connectionString)
    Dim objCmd As SqlCommand
    Dim objDR As SqlDataReader



    Sub CheckCredentials_Click(ByVal s As Object, ByVal e As EventArgs)
        Dim mpTxtUsername As TextBox
        mpTxtUsername = CType(Master.FindControl("txtUsername"), TextBox)
        'If Not mpTxtUsername Is Nothing Then
        '    txtUsername.Text = "Master page label = " + mpTxtUsername.Text
        'End If
        Dim mpTxtPassword As TextBox
        mpTxtPassword = CType(Master.FindControl("txtUsername"), TextBox)
        'If Not mpTxtUsername Is Nothing Then
        '    txtPassword.Text = "Master page label = " + mpTxtUsername.Text
        'End If
    End Sub

    Sub CheckCredentialsLocal_Click(ByVal s As Object, ByVal e As EventArgs)
        Dim email As String = txtEmail.Text
        Dim password As String = txtPassword.Text

        If (CheckCredentials(email, password) = True) Then

            Dim rolesAdapter As New dsAuthTableAdapters.rolesForUserTableAdapter()
            Dim roleTable As New dsAuth.rolesForUserDataTable

            rolesAdapter.FillRolesForUser(roleTable, email)

            Dim roles As String
            Dim counter As Integer = 1

            For Each roleRow As dsAuth.rolesForUserRow In roleTable
                If counter = 1 Then
                    roles = roleRow.Name
                Else
                    roles += "," & roleRow.Name
                End If
                counter += 1
            Next

            Dim userData As String = roles
            Dim ticket As FormsAuthenticationTicket = New FormsAuthenticationTicket(1, UserID, DateTime.Now, DateTime.Now.AddMinutes(60), Persist.Checked, userData, FormsAuthentication.FormsCookiePath)
            ' Encrypt the ticket.
            Dim encTicket As String = FormsAuthentication.Encrypt(ticket)
            ' Create the cookie.
            Response.Cookies.Add(New HttpCookie(FormsAuthentication.FormsCookieName, encTicket))
            ' Redirect back to original URL.
            Response.Redirect(FormsAuthentication.GetRedirectUrl(email, Persist.Checked))
        Else
            Session("userStatus") = "NotAuth"
        End If
    End Sub

    Function CheckCredentials(ByVal email As String, ByVal Password As String) As Boolean
        objConn.Open()
        objCmd = New SqlCommand("SELECT UserID, Salt, Password FROM Users WHERE Email=@Email", objConn)
        objCmd.Parameters.AddWithValue("@Email", email)

        objDR = objCmd.ExecuteReader()
        If Not objDR.Read() Then
            Return False
        Else
            Dim strSalt As String = objDR("Salt")
            Dim strStoredPassword As String = objDR("Password")
            Dim strGivenPassword As String = FormsAuthentication.HashPasswordForStoringInConfigFile(strSalt & Password, "SHA1")
            Label1.Text = strSalt
            Label2.Text = strStoredPassword
            Label3.Text = strGivenPassword
            Session("UserID") = objDR("UserID")
            Response.Cookies("UserID").Value = objDR("UserID")
            UserID = objDR("UserID")

            'If strStoredPassword.Contains(strGivenPassword) = True Then
            '    Return True
            'Else
            '    Return False
            'End If
            Return strGivenPassword = strStoredPassword
        End If
    End Function


    Sub LogAdminAccess()
        Dim conn As SqlConnection
        Dim comm As SqlCommand
        Dim connectionString As String = ConfigurationManager.ConnectionStrings("Henson Family").ConnectionString
        Dim DateTime As DateTime
        DateTime = Date.Now


        conn = New SqlConnection(connectionString)
        comm = New SqlCommand("INSERT INTO AdminLog (UserID, LoginTime) VALUES (@UserID, @LoginTime)", conn)

        comm.Parameters.Add("@UserID", Data.SqlDbType.NVarChar)
        comm.Parameters("@UserID").Value = UserID()
        comm.Parameters.Add("@LoginTime", Data.SqlDbType.DateTime)
        comm.Parameters("@LoginTime").Value = DateTime

        conn.Open()
        comm.ExecuteNonQuery()
        conn.Close()


    End Sub

    Sub Application_AuthenticateRequest()
        If Request.IsAuthenticated Then
            Dim connString As String = ConfigurationManager.ConnectionStrings("Henson Family").ConnectionString
            Dim conn As New SqlConnection(connString)
            Dim comm As New SqlCommand

            conn.Open()

            comm.CommandText = "rolesForUser"
            comm.CommandType = Data.CommandType.StoredProcedure
            comm.Connection = conn
            comm.Parameters.AddWithValue("@FName", User.Identity.Name)

            Dim reader As SqlDataReader

            reader = comm.ExecuteReader

            Dim roleList As New ArrayList

            Do While reader.Read()
                roleList.Add(reader("Name"))
            Loop

            Dim roleListArray As String() = roleList.ToArray(GetType(String))

            HttpContext.Current.User = New GenericPrincipal(User.Identity, roleListArray)
        End If
    End Sub


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim status As Integer = Request.QueryString("status")

        If status = 1 Then
            lblCheck.Text = "You have sucessfully registered. You may now login."
        End If
    End Sub
End Class
